<?php


namespace app\service;


use app\entity\ActQuestionsEntity;
use app\entity\GoodsEntity;
use app\entity\SuggestionEntity;
use app\entity\UserEntity;
use app\exception\ErrorCode;
use app\exception\OaException;
use app\models\request\ReqActListPage;
use app\models\request\ReqAddGoods;
use app\models\request\ReqAppeal;
use app\models\request\ReqAppendQuestion;
use app\models\request\ReqSuggestion;
use app\models\response\RespGoodsDetail;
use app\models\response\RespPage;
use yii\data\Pagination;


class SuggestionService
{

    /**
     * @param $id
     * @param $userId
     * @return array|\yii\db\ActiveRecord|SuggestionEntity
     * @throws OaException
     */
    public function findByIdAndUserId($id,$userId){
        $entity = SuggestionEntity::find()->where(["id"=>$id,"user_id"=>$userId])->one();
        if(!$entity) {
            throw new OaException(ErrorCode::NOT_404);
        }
        return $entity;
    }

    /**
     * @param int $userId
     * @return RespPage
     */
    public function listPage(ReqActListPage $req) {
        $data = SuggestionEntity::find()->where(["del_flag"=>0])->orderBy("id desc");
        $data->andWhere(["user_id"=>$req->getUserId()]);


        $pages = new Pagination(['totalCount' =>$data->count(), 'pageSize' => $req->getPageSize(),'page'=>$req->getPageNo()-1]);
        /**@var $entities SuggestionEntity[]*/
        $entities = $data->offset($pages->getOffset())->limit($pages->getLimit())->all();
        $list = [];
        foreach ($entities as $entity) {

            array_push($list,[
                "id" => $entity->getId(),
                "suggestion" => $entity->getSuggestion(),
                "create_time" => $entity->getCreateTime(),
                "name" => $entity->getName(),
                "phone" => $entity->getPhone(),
                "email" => $entity->getEmail(),
                "status" => $entity->getStatus(),
            ]);
        }

        $resp = new RespPage();
        $resp->setTotal(intval($pages->totalCount));
        $resp->setPageSize($pages->getPageSize());
        $resp->setPageNo($req->getPageNo());
        $resp->setList($list);
        return $resp;
    }


    /**
     * @param $req ReqSuggestion|ReqAppeal
     * @return bool
     * @throws OaException
     */
    public function addSuggestion($req) {

        $key = $req->getPhone()."suggesstion";
        $num = $req->getPhone()."num";


        $redis = UserService::getRedis();
        if ($redis->get($key)) {
            throw new OaException(ErrorCode::OP_PF);
        }

        $cNum = intval($redis->get($num));

        if ($cNum>5) {
            throw new OaException(ErrorCode::USER_S_O);
        }

        $time = date("Y-m-d G:i:s");
        $e = new SuggestionEntity();
        $e->setSuggestion($this->sanitize_input($req->getSuggestion()));
        $e->setCreateTime($time);
        $e->setUpdateTime($time);
        $e->setDelFlag(0);
        $e->setType($this->sanitize_input($req->getType()));
        $e->setName($this->sanitize_input($req->getName()));
        $e->setPhone($this->sanitize_input($req->getPhone()));
        $e->setEmail($this->sanitize_input($req->getEmail()));
        $e->setStatus(0);
        $e->setUserId($req->getUserId());
        if ($req->getUserId()) {

            $userEntity = UserEntity::find()->where(["id"=>$req->getUserId()])->one();
            if ($userEntity) {
                $e->setShopId($userEntity->getShopId());
            }
        }


        if ($e->save() && $req->getUserId()) {



            $entity = new ActQuestionsEntity();
            $entity->setSuggestionId($e->getId());
            $entity->setContent($this->sanitize_input($req->getSuggestion()));
            $entity->setType(0);
            $entity->setCreateTime(date("Y-m-d G:i:s"));
            $entity->setUpdateTime(date("Y-m-d G:i:s"));
            $entity->setDelFlag(0);
            $entity->save();
        }


        $redis->set($key,1);
        $redis->expire($key,3);
        $redis->incr($num);
        $redis->expire($num,3600*24);
        return true;
    }

    function appendQuestion(ReqAppendQuestion $req){
        $suggestion = $this->findByIdAndUserId($req->getSuggestionId(),$req->getUserId());



        if($suggestion->getStatus() == 1 ) {
            throw new OaException(ErrorCode::QUESTION_FINISH);
        }

        if ($suggestion->getReplayType() == 0) {
            throw new OaException(ErrorCode::ADMIN_NO_RESPONSE);
        }
        $entity = new ActQuestionsEntity();
        $entity->setSuggestionId($suggestion->getId());
        $entity->setContent($this->sanitize_input($req->getContent()));
        $entity->setType(0);
        $entity->setCreateTime(date("Y-m-d G:i:s"));
        $entity->setUpdateTime(date("Y-m-d G:i:s"));
        $entity->setDelFlag(0);
        if ($entity->save()) {
            $suggestion->setStatus(0);
            $suggestion->setReplayType(0);
            $suggestion->save();
        }

    }

    function sanitize_input($input) {
        // 去除输入中的 HTML 和 PHP 标记
        $input = strip_tags($input);

        // 转义特殊字符
        $input = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');

        // 返回过滤后的输入
        return $input;
    }

    /**
     * @param $suggestionId
     * @param $userId
     * @return array|\yii\db\ActiveRecord[]|ActQuestionsEntity[]
     * @throws OaException
     */
    public function getSubQuestion($suggestionId,$userId){
        $this->findByIdAndUserId($suggestionId,$userId);
        return ActQuestionsEntity::find()->where(["suggestion_id"=>$suggestionId,"del_flag"=>0])->all();
    }

    public function endQuestion($suggestionId,$userId){
        $entity = $this->findByIdAndUserId($suggestionId,$userId);
        if($entity->getStatus() == 1 ) {
            throw new OaException(ErrorCode::QUESTION_FINISH);
        }
        $entity->setStatus(1);
        $entity->save();
        return true;
    }

}